package com.siwei.mes.config;

import cn.dev33.satoken.stp.StpUtil;
import com.siwei.mes.common.annotation.AnonymousAccess;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenmaolin
 * @date 2021-11-19
 */
@Component
public class SaTokenLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 匿名访问注解
            AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
            if (null != anonymousAccess) {
                return true;
            }
        }
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        StpUtil.checkLogin();
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除对象
    }
}
